list cast c#

68

list cast<> c# -

x.Outputs = grOutputs.Cast<object>().ToList();

list cast<> c# -

var dogs = new List<Dog>();
var pets = (List<object>)dogs;
pets.Add(new Cat());

list cast<> c# -

There are many ways to do that, I think there are two you should consider:

You can use Cast and ToList, but it will require using System.Linq.

var listOfStrings = new List<string>() { "foo", "bar" };
var listOfObjects = listOfStrings.Cast<object>().ToList();

To avoid that, you can use new List<T>(IEnumerable<T> source) constructor. Because IEnumerable<T> is covariant, you can do following:

var listOfStrings = new List<string>() { "foo", "bar" };
var listOfObjects = new List<object>(listOfString);

Comments

Submit
0 Comments